package top.huntwolf.admin.config;


import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import top.huntwolf.admin.common.SpringClassScanner;
import top.huntwolf.admin.common.enums.EnumValue;
import top.huntwolf.admin.common.typeHandler.EnumTypeHandler;

import java.util.List;
import java.util.function.Predicate;

@Configuration
@ConditionalOnClass({SqlSessionFactory.class})
public class MybatisTypeHandlerConfiguration {

    private TypeHandlerRegistry typeHandlerRegistry;

    private final SpringClassScanner springClassScanner;

    public MybatisTypeHandlerConfiguration(SqlSessionFactory sqlSessionFactory,SpringClassScanner springClassScanner) {
        this.typeHandlerRegistry = sqlSessionFactory.getConfiguration().getTypeHandlerRegistry();
        this.springClassScanner = springClassScanner;
    }

    /*注册Mybatis类型注册器*/
    @Autowired
    public void registerTypeHandlers(){
        enumValues().forEach(this::registerEnumTypeHandler);
    }

    /*注册枚举类型的类型转换器*/
    private void registerEnumTypeHandler(Class<?> javaTypeClass){
        register(javaTypeClass, EnumTypeHandler.class);
    }

    /*注册类型转换器*/
    private void register(Class<?> javaTypeClass,Class<?> typeHandlerClass){
        this.typeHandlerRegistry.register(javaTypeClass, typeHandlerClass);
    }


    /*扫描所有 EnumValue实现类并注册到spring中*/
    @Bean
    public List<Class<?>> enumValues(){
        //过滤自定义枚举类
        Predicate<Class<?>> filter = clazz -> clazz.isEnum() && EnumValue.class.isAssignableFrom(clazz);
        return springClassScanner.scanClass("top.huntwolf.admin.common.enums",filter);
    }
}
